/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package create_view_modify;

import cse308.entities.Degreeprogram;
import cse308.entities.Survey;
import cse308.GUIUtilityClass;
import cse308.UserSessionBean;
import cse308.entities.Surveyattainmentlevels;
import cse308.entities.Users;
import cse308.helper_classes.DegreeProgramClass;
import cse308.helper_classes.GeneralTest;
import cse308.helper_classes.SurveyClass;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.http.Part;
import org.omnifaces.util.Faces;

/**
 *
 * @author Aaron
 */
@ManagedBean(name = "surveyBean")
@SessionScoped
public class SurveyBean implements Serializable {

    @ManagedProperty(value = "#{gUIUtilityClass}")
    private GUIUtilityClass utilities;
    @ManagedProperty(value = "#{userSessionBean}")
    private UserSessionBean userSessionBean;
    private List<SurveyClass> surveys = new ArrayList();
    private List<Degreeprogram> allDegreePrograms = new ArrayList();
    private List<String> degreePrograms = new ArrayList();
    private String group;
    private String initiator;
    private String semester;
    private String fileLocation;
    private Part resultsFile;
    private Map<String, Object> peoAttainmentLevel = new HashMap();

    public SurveyBean() {
        surveys = new ArrayList();
    }

    public String createSurveys() {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("CSE_308_ABETPU");
        EntityManager em = emf.createEntityManager();
        this.allDegreePrograms = em.createNamedQuery("Degreeprogram.findAll").getResultList();
        return "CreateSurvey";
    }

    public String createSurvey() {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("CSE_308_ABETPU");
        EntityManager em = emf.createEntityManager();
        List<Survey> surveys = em.createNamedQuery("Survey.findAll").getResultList();
        em.getTransaction().begin();
        Survey newSurvey = new Survey();
        newSurvey.setGroupBelong(group);
        newSurvey.setInitiator(initiator);
        newSurvey.setSemester(semester);
        newSurvey.setResults(GUIUtilityClass.convertToBytesByPart(this.resultsFile));
        newSurvey.setIdentifier(surveys.size() + 1);
        
        
        
        if (utilities.checkPK(newSurvey)) {
            FacesMessage message = new FacesMessage();
            message.setDetail(GUIUtilityClass.createWarning);
            FacesContext.getCurrentInstance().addMessage("form", message);
            return "";
        }
        for (String i : this.degreePrograms) {
            Degreeprogram d = em.find(Degreeprogram.class, i);
            if (d != null) {
                newSurvey.getDegreeprogramCollection().add(d);
                d.getSurveyCollection().add(newSurvey);
            }
        }
        em.persist(newSurvey);
        em.getTransaction().commit();
        return "welcome";
    }

    public String setSurveys() {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("CSE_308_ABETPU");
        EntityManager em = emf.createEntityManager();
        List<Survey> surveys2 = em.createNamedQuery("Survey.findAll").getResultList();
        this.surveys = new ArrayList();
        for (Survey sc2 : surveys2) {
            SurveyClass sc = new SurveyClass(sc2);
            //sc.setDegreePrograms(em);
            //sc.setPeoAttainmentLevel(em);
            for (Degreeprogram i : sc2.getDegreeprogramCollection()) {
                for (Users j : i.getUsersCollection()) {
                    if (j.getUsername().equalsIgnoreCase(userSessionBean.getUsername())) {
                        this.surveys.add(sc);
                    }
                }
            }
        }
        return "Surveys";
    }

    public UserSessionBean getUserSessionBean() {
        return userSessionBean;
    }

    public void setUserSessionBean(UserSessionBean userSessionBean) {
        this.userSessionBean = userSessionBean;
    }

    public List<SurveyClass> getSurveys() {
        return surveys;
    }

    public void setSurveys(List<SurveyClass> surveys) {
        this.surveys = surveys;
    }

    public void getResultsList(ActionEvent ae) {
        try {
            Integer rowIndex = (Integer) ae.getComponent().getNamingContainer().getAttributes().get("rowIndex");
            Faces.sendFile(this.surveys.get(rowIndex).getResultsFile(), true);
        } catch (IOException ex) {
            Logger.getLogger(GUIUtilityClass.class.getName()).log(Level.SEVERE, null, ex);
        }
        //LOG.info("Downloads selected Syllabus");
    }

    public List<Degreeprogram> getAllDegreePrograms() {
        return allDegreePrograms;
    }

    public void setAllDegreePrograms(List<Degreeprogram> allDegreePrograms) {
        this.allDegreePrograms = allDegreePrograms;
    }

    public List<String> getDegreePrograms() {
        return degreePrograms;
    }

    public void setDegreePrograms(List<String> degreePrograms) {
        this.degreePrograms = degreePrograms;
    }

    public String getGroup() {
        return group;
    }

    public void setGroup(String group) {
        this.group = group;
    }

    public String getInitiator() {
        return initiator;
    }

    public void setInitiator(String initiator) {
        this.initiator = initiator;
    }

    public String getSemester() {
        return semester;
    }

    public void setSemester(String semester) {
        this.semester = semester;
    }

    public String getFileLocation() {
        return fileLocation;
    }

    public void setFileLocation(String fileLocation) {
        this.fileLocation = fileLocation;
    }

    public Part getResultsFile() {
        return resultsFile;
    }

    public void setResultsFile(Part resultsFile) {
        this.resultsFile = resultsFile;
    }

    public Map<String, Object> getPeoAttainmentLevel() {
        return peoAttainmentLevel;
    }

    public void setPeoAttainmentLevel(Map<String, Object> peoAttainmentLevel) {
        this.peoAttainmentLevel = peoAttainmentLevel;
    }

    public void getSurveyResultFile(ActionEvent ae) {
        try {
            Integer rowIndex = (Integer) ae.getComponent().getNamingContainer().getAttributes().get("rowIndex");
            File sendTo = this.surveys.get(rowIndex).getResultsFile();
            if (sendTo == null) {
                return;
            }
            Faces.sendFile(sendTo, true);
        } catch (IOException ex) {
            Logger.getLogger(GUIUtilityClass.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void saveAttainment(ActionEvent ae) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("CSE_308_ABETPU");
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        Integer rowIndex = (Integer) ae.getComponent().getNamingContainer().getParent().getParent().getAttributes().get("rowIndex");
        SurveyClass sc = this.surveys.get(rowIndex);
        Survey s = (Survey) sc.findCorrespondingEntity();
        String peo = sc.getCurrentPEO();
        Collection<Surveyattainmentlevels> satll = s.getSurveyattainmentlevelsCollection();
        for (Surveyattainmentlevels satl : satll) {
            if (satl.getSurveyattainmentlevelsPK().getPeo().equals(sc.getCurrentPEO())) {
                satl.setAttinmentlevel(sc.getCurrentAttainment());
                em.merge(satl);
                em.getTransaction().commit();
                break;
            }
        }
    }

    public String modifySurveys() {
        List<String> associatedClasses = new ArrayList();
        associatedClasses.add(DegreeProgramClass.class.getCanonicalName());
        List<String> associatedEntities = new ArrayList();
        associatedEntities.add(Degreeprogram.class.getCanonicalName());
        List<String> allSet = new ArrayList();
        allSet.add("setAllDegreePrograms");
        List<String> ownSet = new ArrayList();
        ownSet.add("setOwnDegreePrograms");
        try {
            this.surveys = (List) this.utilities.generalizeModify(Survey.class.getCanonicalName(), SurveyClass.class.getCanonicalName(),
                    associatedClasses, associatedEntities, ownSet, allSet);
        } catch (ClassNotFoundException | NoSuchMethodException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
            Logger.getLogger(SurveyBean.class.getName()).log(Level.SEVERE, null, ex);
        }
        return "ModifySurvey";
    }

    public String saveSurveys() {
        List<GeneralTest> gt = new ArrayList();
        for (SurveyClass sc : this.surveys) {
            gt.add(sc);
        }

        List<String> innerQueries = new ArrayList();
        innerQueries.add(Degreeprogram.class.getSimpleName());
        try {
            boolean success = this.utilities.generalizedSave(Survey.class.getCanonicalName(), gt, innerQueries);
            if (!success) {
                FacesMessage message = new FacesMessage();
                message.setDetail(GUIUtilityClass.duplicateWarning);
                FacesContext.getCurrentInstance().addMessage("form", message);
                return "";
            }
        } catch (SecurityException | NoSuchFieldException | IllegalArgumentException | IllegalAccessException | NoSuchMethodException | InvocationTargetException | ClassNotFoundException | InstantiationException ex) {
            Logger.getLogger(SurveyBean.class.getName()).log(Level.SEVERE, null, ex);
        }
        return "ModifySurvey";
    }

    public GUIUtilityClass getUtilities() {
        return utilities;
    }

    public void setUtilities(GUIUtilityClass utilities) {
        this.utilities = utilities;
    }
}